//
//  WSSNetTool.m
//  Cicada
//
//  Created by dllo on 16/5/11.
//  Copyright © 2016年 dllo. All rights reserved.
//

#import "WSSNetTool.h"
#import "AFNetworking.h"
//菊花
#import "MBProgressHUD.h"
#import "Reachability.h"
//MD5加密
#import <CommonCrypto/CommonCrypto.h>

@implementation WSSNetTool

#pragma mark -- 根据一个字符串返回一个MD5加密字符串
+ (NSString *)cachedFileNameForKey:(NSString *)key {
    const char *str = [key UTF8String];
    if (str == NULL) {
        str = "";
    }
    unsigned char r[CC_MD5_DIGEST_LENGTH];
    CC_MD5(str, (CC_LONG)strlen(str), r);
    NSString *filename = [NSString stringWithFormat:@"%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x",
                          r[0], r[1], r[2], r[3], r[4], r[5], r[6], r[7], r[8], r[9], r[10], r[11], r[12], r[13], r[14], r[15]];
    return filename;
}

+(void)GetNetByURL:(NSString *)urlString body:(id)body headers:(NSDictionary *)headers response:(WSSResponseStyle)response success:(blockofSuccess)success failure:(blockofFailure)failure
{
    //1.获取网络管理者
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    
    //2.请求头的设置
    if (headers)//如果有请求头
    {
        for (NSString *key in headers.allKeys)
        {
            [manager.requestSerializer setValue:headers[key] forHTTPHeaderField:key];
        }
    }
    
    //3.设置返回数据的类型
    switch (response)
    {
        case WSSJSON:
            manager.responseSerializer = [AFJSONResponseSerializer serializer];
            break;
        case WSSXML:
            manager.responseSerializer = [AFXMLParserResponseSerializer serializer];
            break;
        case WSSDATA:
            manager.responseSerializer = [AFHTTPResponseSerializer serializer];
            break;
            
        default:
            break;
    }
    
    //4.设置响应数据的类型
    [manager.responseSerializer setAcceptableContentTypes:[NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript",@"text/html",@"text/css",@"text/plain", @"application/javascript",@"image/jpeg", @"text/vnd.wap.wml", nil]];

    //5.若有汉语进行UTF8转码(这个方法是iOS9之后的方法)
    urlString = [urlString stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
    Reachability *wifi = [Reachability reachabilityForLocalWiFi];
    Reachability *conn = [Reachability reachabilityForInternetConnection];
    
    NSString *cachePath = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask , YES).lastObject;
    
    NSString *filePath = [cachePath stringByAppendingPathComponent:[self cachedFileNameForKey:urlString]];
    
    if ([wifi currentReachabilityStatus] != NotReachable || [conn currentReachabilityStatus] != NotReachable) {
        //NSLog(@"使用的wifi");
        //6.发送请求
        [manager GET:urlString parameters:body progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            success(responseObject);
            BOOL isCache = [NSKeyedArchiver archiveRootObject:responseObject toFile:filePath];
            if (isCache) {
                NSLog(@"缓存成功");
            }
            else
            {
                NSLog(@"缓存失败");
            }
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            failure(error);
            NSLog(@"%@", error);
            id data = [NSKeyedUnarchiver unarchiveObjectWithFile:filePath];
            if (data) {
                success(data);
            }
        }];
    }
    else
    {
        NSLog(@"使用的缓存");
        id data = [NSKeyedUnarchiver unarchiveObjectWithFile:filePath];
        if (data) {
            success(data);
        }
        else
        {
            [manager GET:urlString parameters:body progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
                failure(error);
                
            }];
        }
    }
}

+ (void)PostNetByURL:(NSString *)urlString body:(id)body bodyStyle:(WSSRequestStyle)bodyStyle headers:(NSDictionary *)headers response:(WSSResponseStyle)response success:(blockofSuccess)success failure:(blockofFailure)failure
{
    //1.获取网络管理者
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    
    //2.设置body数据类型
    switch (bodyStyle) {
        case WSSBodyJSON:
            manager.requestSerializer = [AFJSONRequestSerializer serializer];
            break;
        case WSSBodyString:
            [manager.requestSerializer setQueryStringSerializationWithBlock:^NSString * _Nonnull(NSURLRequest * _Nonnull request, id  _Nonnull parameters, NSError * _Nullable * _Nullable error) {
                return parameters;
            }];
            break;
            
        default:
            break;
    }
    
    //3.请求头的设置
    if (headers)//如果有请求头
    {
        for (NSString *key in headers.allKeys)
        {
            [manager.requestSerializer setValue:headers[key] forHTTPHeaderField:key];
        }
    }
    
    //4.设置返回数据的类型
    switch (response) {
        case WSSJSON:
            manager.responseSerializer = [AFJSONResponseSerializer serializer];
            break;
        case WSSXML:
            manager.responseSerializer = [AFXMLParserResponseSerializer serializer];
            break;
        case WSSDATA:
            manager.responseSerializer = [AFHTTPResponseSerializer serializer];
            break;
            
        default:
            break;
    }
    
    //5.设置响应数据的类型
    [manager.responseSerializer setAcceptableContentTypes:[NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript",@"text/html",@"text/css",@"text/plain", @"application/javascript",@"image/jpeg", @"text/vnd.wap.wml", nil]];
    
    //设置可请求https
    manager.securityPolicy.allowInvalidCertificates = YES;
    
    //6.若有汉语进行UTF8转码(这个方法是iOS9之后的方法)
    urlString = [urlString stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
    
    //7.发送请求
    [manager POST:urlString parameters:body progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        //成功block回调
        success(responseObject);
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"失败原因:%@", error);
        //失败block回调
        failure(error);
    }];
}




//实验 **********************
+ (void)GetNet2ByURL:(NSString *)urlString body:(id)body headers:(NSDictionary *)headers response:(WSSResponseStyle)response success:(blockofSuccess)success failure:(blockofFailure)failure selfView:(UIView *)selfView
{

    
    //1.获取网络管理者
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    
    //2.请求头的设置
    if (headers)//如果有请求头
    {
        for (NSString *key in headers.allKeys)
        {
            [manager.requestSerializer setValue:headers[key] forHTTPHeaderField:key];
        }
    }
    
    //3.设置返回数据的类型
    switch (response)
    {
        case WSSJSON:
            manager.responseSerializer = [AFJSONResponseSerializer serializer];
            break;
        case WSSXML:
            manager.responseSerializer = [AFXMLParserResponseSerializer serializer];
            break;
        case WSSDATA:
            manager.responseSerializer = [AFHTTPResponseSerializer serializer];
            break;
            
        default:
            break;
    }
    
    //4.设置响应数据的类型
    [manager.responseSerializer setAcceptableContentTypes:[NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript",@"text/html",@"text/css",@"text/plain", @"application/javascript",@"image/jpeg", @"text/vnd.wap.wml", nil]];
    
    //5.若有汉语进行UTF8转码(这个方法是iOS9之后的方法)
    urlString = [urlString stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
    

    //添加菊花
    MBProgressHUD *mbView = [MBProgressHUD showHUDAddedTo:selfView animated:YES];
    mbView.detailsLabelText = @"请耐心等待,网络加载中";
    
    //6.发送请求
    [manager GET:urlString parameters:body progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        //成功block回调
        success(responseObject);
        //取消菊花
        [mbView hide:YES];

    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"失败原因:%@", error);
        //取消菊花
        [mbView hide:YES];
        //失败block回调
        failure(error);
    }];
  
}

@end
